#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/7/16 15:43
# @Author    :cjw
from typing import List

from fastapi.encoders import jsonable_encoder
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.item import Item
from app.schemas.item import ItemCreate, ItemUpdate
from app.crud.base import CRUDBase


class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]):

	def create_with_owner(self, db: Session, *, obj_in: ItemCreate,
	                      owner_id: int) -> Item:
		"""
		创建项目数据
		:param db: 数据库连接
		:param obj_in: 项目创建模型
		:param owner_id: 拥有者id
		:return:
		"""
		obj_in_data = jsonable_encoder(obj_in)
		db_obj = self.model(**obj_in_data, owner_id=owner_id)
		db.add(db_obj)
		db.commit()
		return db_obj

	def get_multi_by_owner(self, db: Session, *, owner_id: int, skip: int = 0,
	                       limit: int = 100) -> List[Item]:
		"""
		根据用户id，获取多个项目数据
		:param db: 数据库连接
		:param owner_id: 拥有者id
		:param skip: 查询起始位置
		:param limit: 限制的查询条数
		:return:
		"""
		stmt = select(self.model).where(Item.owner_id == owner_id).offset(skip).limit(limit)

		return [st for st in db.execute(stmt).scalars()]


item = CRUDItem(Item)
